package com.elem.web;

import com.elem.bean.DeliveryAddress;
import com.elem.service.DeliveryAddressService;
import com.elem.service.impl.DeliveryAddressServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "DeliveryAddressServlet", value = "/DeliveryAddressController/*")
public class DeliveryAddressServlet extends BaseServlet {
    DeliveryAddressService deliveryAddressService = new DeliveryAddressServiceImpl();
    ObjectMapper objectMapper = new ObjectMapper();

        public DeliveryAddress getDeliveryAddressById(HttpServletRequest req, HttpServletResponse resp) throws Exception {
           String daId = req.getParameter("daId");

            try {
                DeliveryAddress deliveryAddress=deliveryAddressService.getDeliveryAddressById(daId);
                objectMapper.writeValue(resp.getOutputStream(), deliveryAddress);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }


            return null;
        }


        public int saveDeliveryAddress(HttpServletRequest req, HttpServletResponse resp) throws Exception {

            DeliveryAddress deliveryAddress=new DeliveryAddress();
            BeanUtils.populate(deliveryAddress,req.getParameterMap());
            int row = deliveryAddressService.saveDeliveryAddress(deliveryAddress);
            objectMapper.writeValue(resp.getOutputStream(), row);
            return 0;
        }


        public List<DeliveryAddress> listDeliveryAddressByUserId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
            String userId = req.getParameter("userId");
            List<DeliveryAddress> list = deliveryAddressService.listDeliveryAddressByUserId(userId);
            objectMapper.writeValue(resp.getOutputStream(), list);
            return null;
        }


        public int removeDeliveryAddress(HttpServletRequest req, HttpServletResponse resp) throws Exception {
            DeliveryAddress deliveryAddress=new DeliveryAddress();
            BeanUtils.populate(deliveryAddress,req.getParameterMap());
            int row = deliveryAddressService.removeDeliveryAddress(deliveryAddress);
            objectMapper.writeValue(resp.getOutputStream(), row);
            return 0;
        }


        public int updateDeliveryAddress(HttpServletRequest req, HttpServletResponse resp) throws Exception {
            DeliveryAddress deliveryAddress=new DeliveryAddress();
            BeanUtils.populate(deliveryAddress,req.getParameterMap());
            int row = deliveryAddressService.updateDeliveryAddress(deliveryAddress);
            objectMapper.writeValue(resp.getOutputStream(), row);
            return 0;
        }



}
